package com.simafei.flow.core.operator.impl;

import cn.hutool.core.util.NumberUtil;
import com.simafei.flow.core.common.CalcType;
import com.simafei.flow.core.common.Criterion;
import com.simafei.flow.core.common.ExpressionExecutor;
import com.simafei.flow.core.common.Operator;
import com.simafei.flow.core.operator.OperatorHandler;

import java.util.List;
import java.util.Map;

/**
 * @author fengpengju
 */
public class LikeOperatorHandler implements OperatorHandler {

    @Override
    public String handle(Criterion condition) {
        String right = condition.getRight();
        if (condition.getRightType() == CalcType.CONSTANT) {
            // 如果是变量直接交给引擎
            if (!NumberUtil.isNumber(right)) {
                // 常量字符串需要加单引号
                right = "'" + right + "'";
            }
        }
        return condition.getLeft() + ".contains(" + right + ")";
    }

    @Override
    public List<String> sqlRight(Criterion condition, Map<String, Object> params) {
        String right = condition.getRight();
        if (condition.getRightType() == CalcType.CONSTANT) {
            return List.of(right);
        } else {
            Object rightValue = ExpressionExecutor.execute(right, params);
            return List.of("%" + rightValue + "%");
        }
    }


    @Override
    public boolean support(Operator operator) {
        return Operator.LIKE == operator;
    }

}
